<template>
  <div class="home-container" >
    <v-touch v-on:swipeleft="swiperleft" v-on:swiperight="swiperright"   class="v-touch">
      <van-image  :src="resources.bgTop" class="bg-top"  v-show="$store.state.workbenchActive"/>
      <div v-show="$store.state.workbenchActive" class="head-box">
        <van-row>
          <van-col span="24">
            <h3 style="margin-bottom: 10px;">欢迎使用医院物资精益化管理信息系统</h3>
          </van-col>
        </van-row>
        <van-row  type="flex" justify="center">
          <van-col span="12" class="col-left">
           <p class="user-name"><span>用户：</span>{{ user.name }} &nbsp; ({{ user && user.workNo ? user.workNo : "暂无"}})</p>
           <p class="user-dept"><span>部门：</span>{{ user && user.deptName ? user.deptName : "暂无" }}</p>

          </van-col>
          <van-col span="12"  class="col-right">
            <p><van-icon name="setting-o" size="20"  @click="handleSetup"  class="bg-location" /></p>
            <p class="text-warehouse">{{warehouseName}}</p>
          </van-col>
        </van-row>
      </div>


    <!-- 顶部操作按钮-->
      <div v-show="!$store.state.workbenchActive" ref="rvContainer" class="router-view-container">
        <van-sticky :offset-top="0" class="box-top" v-show="nowRouteName != 'app_system_index'">
          <van-nav-bar
            right-text=""
            left-arrow
            @click-left="handleBack"
          >
            <template #title>
              <van-icon name="wap-home-o" @click="handleBackHome" class="center-icon"/>
              {{$store.getters.currentWarehouse.name}}
              <span class="center-title">{{nowTitle}}</span>
            </template>
            <template #right>
              <van-icon name="replay" size="18" @click="handleReload" />
            </template>
          </van-nav-bar>
        </van-sticky>
        <transition :name="transitionName" >
          <router-view style="width: 100%" ref="routerView" class="box-main"></router-view>
        </transition>
      </div>

     <!-- 中间操作按钮-->
      <transition :name="transitionName">
        <div v-show="$store.state.workbenchActive" ref="workbench" style="width: 100%" class="btn-box">
            <div ref="menuArea" style="width: 100%; font-size: 14px">
              <van-tabs animated swipeable >
                <van-tab v-for="(menu2,index0) in cpMenu2" :key="menu2.id" :name="menu2.name"  >
                  <template #title><van-icon :name="menu2.icon" />{{menu2.title}}</template>
                  <van-grid :class="'menu-grid menu-grid-'+index0" :column-num="3" square clickable :icon-size="13" :style="{overflow: 'auto', maxHeight: winH-250 +'px'}">
                    <van-grid-item  v-for="(menu3, index) in getChildMenu(menu2.id)" :key="menu3.key" style="padding-top: 30%;"  @click="handleSelectMenu(menu3)">
                      <van-icon class="ico÷n-menu" :name="menu3.icon" size="40" :color="iconColor[index]" />
                      <span class="icon-text">{{menu3.title}} </span>
                    </van-grid-item>
                  </van-grid>
                </van-tab>
              </van-tabs>
            </div>
        </div>
      </transition>

      <!--底部操作栏-->
      <div class="footer" v-show="active >= 0">
        <van-tabbar v-model="active" active-color="#07c160" inactive-color="#000">
          <van-tabbar-item   @click="handleBackHome">
            <span class="tabbar-text">主页</span>
            <template #icon="props">
              <van-image  :src="resources.homeCheck" class="icon-left"  v-show="nowRouteName == 'dashboard'"/>
              <van-image  :src="resources.homeUnCheck" class="icon-left"  v-show="nowRouteName != 'dashboard'"/>
            </template>
          </van-tabbar-item>
          <van-tabbar-item icon="setting-o"  @click=" $store.commit('SET_WORKBENCH_ROUTE', { name: 'app_system_index', params: {active: 1} })">
            <span class="tabbar-text">个人中心</span>
            <template #icon="props">
              <van-image  :src="resources.meCheck" class="icon-left"  v-show="nowRouteName == 'app_system_index'"/>
              <van-image  :src="resources.meUnCheck" class="icon-left"  v-show="nowRouteName != 'app_system_index'"/>
            </template>
          </van-tabbar-item>
          <!--  <van-tabbar-item icon="search">数据报表</van-tabbar-item>
          <van-tabbar-item icon="friends-o" badge="3">操作记录</van-tabbar-item>-->
        </van-tabbar>
      </div>
    </v-touch>

    <!--选择工位-->
    <FortenList ref="listItem" :propAutoFetchData = 'false'
                :propIsRadio="true"
                :propFlagPopup="true"
                :propSearchFields="['name']"
                :propSearchTextAppend="'名称/代码'"
                propUrl="/base/warehouse/pageForSelect"
                @change="whCheckChange"
    >
      <template  #default="{item}"  >
        <van-row >
          <van-col span="4">
            <van-radio   :name="item"  />
          </van-col>
          <van-col span="4">名称：</van-col>
          <van-col span="8">{{item.name}}</van-col>
          <van-col span="4">代码：</van-col>
          <van-col span="4">{{item.code}}</van-col>
        </van-row>
        <van-row  >
          <van-col span="4">
          </van-col>
          <van-col span="4">地址：</van-col>
          <van-col span="14">{{item.address}}</van-col>
        </van-row>
      </template>

    </FortenList>

<!--    <van-popup position="bottom" closeable v-model="selectVisible" >
      <van-sticky :offset-top="0">
        <van-field ref="searchValue" autofocus="true"   label="搜索" placeholder="请输入" v-model="searchValue"  @input="handlePageSearch"/>
      </van-sticky>
      <van-radio-group v-model="warehouseId" @change="whCheckChange">
        <van-cell-group>
          <van-cell v-for="item in searchedList" :key="item.id" :title="item.warehouseName" clickable >
            <template #right-icon>
              <van-radio :name="item.id" />
            </template>
          </van-cell>
        </van-cell-group>
      </van-radio-group>
    </van-popup>-->

    <section >
      <!--打印区域-->
      <div ref="printBox" id="printBox" class="print-box"  >
        <div class="dataTableBox"  v-for="(row,index0) in printrows" :key="index0" :style="{padding:'0px 0px 0px 5px'}">
          <table style="table-layout:fixed;padding-left: 11px;border-spacing: 0px">
            <tr >
              <td    colspan="2" style="padding: 0px; padding-left: 27px;">
                <FortenCode
                  propType="barcode"
                  :propValue="row.sn"
                  propHeight="40"
                  style="zoom: 100%; height: 41px"
                >
                </FortenCode>
                <div style="font-size: 8px; zoom: 100%; line-height: 11px; ">
                  {{row.sn}}
                  <strong style="padding-left: 3px">{{row.flagOmoc ? '高' : '低'}}</strong>
                </div>
              </td>
            </tr>
            <tr>
              <td colspan="2"  style="padding: 0px;">
                <table style="table-layout:fixed;border-spacing: 0px; padding: 0px">
                  <tr>
                    <td :style="getStyle(true)" v-if="!isHide('hrpCode')">
                      编码
                    </td>
                    <!--                  <td :style="getStyle()" >-->
                    <!--                    {{row.mscmCode}}({{row.flagOmoc ? '高耗' : '低耗'}})-->
                    <!--                  </td>-->
                    <td :style="getStyle()" v-if="!isHide('hrpCode')">
                      {{row.hrpCode}}
                    </td>
                    <td :style="getStyle(true)" v-if="!isHide('packageUnit')">
                      包装
                    </td>
                    <td :style="getStyle()" v-if="!isHide('packageUnit')">
                      {{row.packageUnit}}({{row.skuUnit}}/{{row.skuQty}})
                    </td>
                  </tr>
                </table>
              </td>
            </tr>
            <tr>
              <td :style="getStyle(true)" v-if="!isHide('matrName')">
                耗材
              </td>
              <td :style="getStyle()" v-if="!isHide('matrName')">
                <div  :style="getTdMaxWidth()">
                  {{row.matrName}}
                </div>
              </td>
            </tr>
            <tr>
              <td :style="getStyle(true)" v-if="!isHide('matrSpec')">
                品规
              </td>
              <td :style="getStyle()" v-if="!isHide('matrSpec')">
                {{row.matrSpec}}
              </td>
            </tr><!--
          <tr>
            <td :style="getStyle(true,true)" v-if="!isHide('sn')">
              SN
            </td>
            <td :style="getStyle()" v-if="!isHide('sn')">
              {{row.sn}}
              <strong style="padding-left: 3px">{{row.flagOmoc ? '高值■' : '低值▲'}}</strong>
            </td>
          </tr>-->
            <tr>
              <td   colspan="2" style="padding: 0px;">
                <table style="table-layout:fixed;border-spacing: 0px; padding: 0px">
                  <tr>
                    <td :style="getStyle(true)" v-if="!isHide('lot')">
                      批次
                    </td>
                    <td :style="getStyle()" v-if="!isHide('lot')">
                      {{row.lot}}
                    </td>
                    <td :style="getStyle(true)" v-if="!isHide('expDate')">
                      效期
                    </td>
                    <td :style="getStyle()" v-if="!isHide('expDate')">
                      {{dates.toDate(row.expDate, 'yyyy-MM-dd')}}
                    </td>
                  </tr>
                </table>
              </td>
            </tr>
            <tr>
              <td :style="getStyle(true)" v-if="!isHide('mfgName')">
                厂商
              </td>
              <td :style="getStyle()" v-if="!isHide('mfgName')">
                <div  :style="getTdMaxWidth()">
                  {{row.mfgName}}
                </div>
              </td>
            </tr>
            <tr>
              <td :style="getStyle(true)" v-if="!isHide('udi')">
                UDI
              </td>
              <td :style="getStyle()" v-if="!isHide('udi')">
                <div  :style="getTdMaxWidth(true)">
                  {{strings.defaultIfBlank(row.udi, '')}}
                </div>
              </td>
            </tr>
          </table>
        </div>
      </div>
    </section>


    <!--rfid扫描枪界面-->
    <van-popup v-model="showRfidScan" position="bottom" style="padding: 30px 5px ; height:  250px" :close-on-click-overlay="false">
      <van-row type="flex" justify="space-around" >
        <van-col span="24" style="text-align: center">
          <h3>RFID 盘询</h3>
        </van-col>
      </van-row>
      <van-row type="flex" justify="space-around" >
          <van-col span="6">
            <van-button type="primary" block @click="rfidScan(1)" size="large" round  :disabled="scanBegin" >
              开始盘询
            </van-button>
          </van-col>
          <van-col span="6">
            <van-button type="warning" block @click="rfidScan(2)" size="large" round   :disabled="!scanBegin">
              结束盘询
            </van-button>
          </van-col>
          <van-col span="6">
            <van-button type="default" block @click="rfidScan(4)" size="large" round   >
              取消
            </van-button>
          </van-col>
        </van-row>
      <van-row type="flex" justify="space-around" style="padding: 5px ; text-align:  center">
        <van-col span="6">
          开始轮询扫描
        </van-col>
        <van-col span="6">
          结束轮询扫描
        </van-col>
        <van-col span="6">
          放弃本次操作
        </van-col>
      </van-row>
        <!--<van-row type="flex" justify="space-around"  style="padding: 5px ; text-align:  center">
          <van-col span="24" style="text-align: center">
            <h4 >{{rfidScanMsg}}</h4>
          </van-col>
      </van-row>-->
    </van-popup>
  </div>
</template>
<style lang="scss" >
@import '../styles/version1/home_index.scss';
</style>
<script>
import {  Dialog, Field, RadioGroup, Radio, Sticky     } from 'vant'
import Warehouse from '@/views/dashboard/Warehouse'
import FortenCode from '@/components/FortenCode.vue'

export default {
  data() {
    return {
      menus: [],
      routes: [],
      active: 0,
      selectedMenu: {},
      user: {},
      /*eslint-disable*/
      logoCenter: require('@/assets/img/home/logo-center.png'),
      selectVisible: false,
      searchValue: "",
      warehouseName: '未设置',
      warehouseId: '',
      whCheck: '',
      searchedList: [],
      warehouseList: [],
      transitionName: '',
      printrows: [],
      showRfidScan: false,
      scanBegin: false,
      scanEnd: false,
      rfidScanMsg: '',
      rfidList: [],
      iconColor: ['blueviolet','orange','powderblue','greenyellow','Salmon','pink','purple','paleturquoise1', 'aquamarine1', 'pink1', 'lightgreen'],
      winH: window.innerHeight,
      resources: {
        /*eslint-disable*/
        bgTop: require('@/assets/img/home/bg_top.png'),
        location: require('@/assets/img/home/icon_location.png'),
        homeCheck: require('@/assets/img/home/home_check.png'),
        homeUnCheck: require('@/assets/img/home/home_uncheck.png'),
        meCheck: require('@/assets/img/home/me_check.png'),
        meUnCheck: require('@/assets/img/home/me_uncheck.png'),
      },
      //当前操作的路由标题
      nowTitle: '',
      //当前操作的路由名称
      nowRouteName: 'dashboard',

      // 图标映射
      menuIconMap: {
        //采购入库
        'app/in-order': require('@/assets/img/home/menu/warehouse/采购入库.png'),
      },
      // 是否主页
      isHome: true,
      // 退出次数
      backNum: 0
    }
  },
  computed: {
    cpRootMenu() {
      return this.$store.getters.menuGetter.find(menu => menu.parentId == 0)
    },
    isHide() {
      return (col) => {
        // if (this.hideColumns && this.hideColumns instanceof Array && this.hideColumns.length > 0) {
        //   return this.hideColumns.some(hide => hide == col)
        // }
        return false
      }
    },
    cpMenu2() {
      const root = this.$store.getters.menuGetter.find(menu => menu.code == 'approot')
      if (root) {
        return this.getChildMenu(root.id)
      } else {
        return []
      }
    },
    avatarUrl() {
      let avatarUrl = this.utils.getCurrentUser().thumbnailImageUrl
      if (avatarUrl === undefined || avatarUrl === null) {
        // eslint-disable-next-line global-require
        avatarUrl = require('@/assets/img/home/user-default.png')
      }
      return avatarUrl
    },
    //全局搜索
    handlePageSearch(key) {
      this.searchedList = this.warehouseList.filter(warehouse => warehouse.warehouseName.indexOf(this.searchValue) > -1
        || this.pyutils.getAllFirstLetter(warehouse.warehouseName).toLowerCase().indexOf(this.searchValue.toLowerCase()) > -1
        || this.pyutils.chineseToPinYin(warehouse.warehouseName).toLowerCase().indexOf(this.searchValue.toLowerCase()) > -1)
    },
    cpRfidList() {
      return window.rfidList.length
    },

  },
  beforeMount() {
    // 加载字典、参数
    this.$ajax.get('/sys/dict_data/all', {
      params: {excludeCommonFields: true}
    }).then(resp => {
      this.$store.dispatch('setDictDataList', resp.data)
    }).finally(() => {
    })


  },
  mounted() {
    console.log("this.utils.getCurrentUser().user", this.utils.getCurrentUser().user)
    this.initData()
    this.getByCurrentUser()
    this.handleBackHome()
    let that = this
    //android 返回键 返回 '1'：则执行物理按键返回功能
    window.androidBackCall = function (){
      console.info('androidBack-home ')
      if (that.isHome) {
        that.$dialog.confirm({
          title: '系统提示',
          message: '确定退出登录么',
        })
          .then(() => {
            window.androidBackCall = null
            that.$store.dispatch('logout')
          }).catch(() => {})
      } else {
        that.handleBack()
      }
      return false
    }
  },
  methods: {
    getChildMenu(parentId) {
      const menus = this.$store.getters.menuGetter
      return menus.filter(item => item.parentId == parentId && item.code != 'app_setup' && item.code != 'app_nomenu')
    },
    handleSelectMenu(menu) {
      if (this.strings.isNotBlank(menu.viewKey)) { //包含视图标识的，使用模板
        this.$store.commit('SET_WORKBENCH_ROUTE', { name: 'fortenDataviewModel', that: this, params: {viewKey: menu.viewKey, flowKey: menu.flowKey}  })
      } else if (menu.route) {
        this.$store.commit('SET_WORKBENCH_ROUTE', { name: menu.route, that: this })
      } else {
        this.$notify.warning('未设置菜单路由')
      }
    },
    handleBack() {
      let len = history.length;
      let ret = this.$router.back(-(len-1))
    },
    handleBackHome() {
      this.utils.vibrate()
      this.$store.commit('SET_WORKBENCH_ROUTE', { name: 'dashboard' })
    },

    //重载页面数据
    handleReload() {
      this.utils.vibrate()
      //包含reload方法
      if (this.$refs.routerView.reload) {
        this.$refs.routerView.reload(true)
        this.$notify.success('刷新完成')
        return
      }

      //清空data里面的数据
      Object.keys(this.$refs.routerView.$data).forEach(key => {
        if (['baseApi', 'fileRefTable'].includes(key) || key.toLowerCase().indexOf('active') != -1) return true
        let ob = this.$refs.routerView.$data[key]
        let valueNew = ''  //[object String]
        switch(Object.prototype.toString.call(ob) ) {
          case '[object Object]':
            valueNew = {}
            break;
          case '[object Array]':
            valueNew = []
            break;
          case '[object Boolean]':
            valueNew = false
            break;
          case '[object Number]':
            valueNew = 0
            break;
        }
        this.$refs.routerView.$data[key] = valueNew
      })
      this.$notify.success('刷新完成')
    },
    initData() {
      // 加载字典
      let getDictData = this.$ajax.get('/sys/dict_data/all', {
        params: {onlyBusFields: true}
      })

      // 加载系统参数
      let getParams = this.$ajax.get('/cfg/parameter/all', {
        params: {onlyBusFields: true}
      })
      let getUserInfo = this.$ajax.get('/user/info')
      let that = this
      Promise.all([getDictData, getParams, getUserInfo]).then(res => {
        let [{data: dds}, {data: params}, {data: user}] = res
        this.$store.dispatch('setDictDataList', dds)
        this.$store.dispatch('setParameterList', params)
        this.$store.dispatch('setCurrentUser', user)
        that.user = user.user
        console.log('that.user----', that.user)

      })
        .finally(() => {
        })
    },
    handleSetup() {
      //振动效果
      this.utils.vibrate()
      this.$refs.listItem.show()
    },
    setCurrent(warehouse) {
      if (!warehouse) {
        warehouse = { id: '', name: '未配置' }
      }
      this.warehouseId = warehouse.id
      this.warehouseName = warehouse.warehouseName
      this.$store.commit('SET_CURRENT_WAREHOUSE', warehouse)
      localStorage.setItem('current_warehouse', JSON.stringify(warehouse))
    },
    whCheckChange(item){
      item.warehouseName = item.name
      this.setCurrent(item)
    },
    getByCurrentUser() {
      this.$ajax.get('/base/user_warehouse/getByCurrentUser').then(res => {
        if (res.code == 0) {
          /*eslint-disabled*/
          this.warehouseList = res.data || []
          let  warehouse = null
          this.searchedList = res.data || []
          if(this.warehouseList.length == 0){
            Dialog.alert({
              title: '系统提示',
              message: '当前用户尚未分配仓库权限，请联系运营',
            })
            this.setCurrent(null)
            return
          }else{
            let currentWarehouse = JSON.parse(localStorage.getItem('current_warehouse'))
            //获取本地存储的仓库信息
            if (currentWarehouse)   warehouse = this.warehouseList.find(item => item.id == currentWarehouse.id)

            if (!warehouse){
              //只有一个仓库则默认选中
              if(this.warehouseList.length == 1)  warehouse = this.warehouseList[0]

              //多个仓库获取默认仓库
              if(!warehouse) warehouse = this.warehouseList.find(item => item.flagDefault == 1)

              if(!warehouse){
                Dialog.alert({
                  title: '系统提示',
                  message: `您有${this.warehouseList.length}个仓库权限，请自行选择，或者联系运营人员设置科室默认仓库`,
                })
                  .then(() => {
                    this.handleSetup()
                  })
              }
            }
          }
          this.setCurrent(warehouse)
        }
      })
    },

    //左滑动
    swiperleft: function () {
      let routeName = this.$route.name
      if (routeName == 'dashboard' || routeName == 'home') { //首页左滑，切换到系统设置
        // this.$store.commit('SET_WORKBENCH_ROUTE', { name: 'app_system_index', params: {active: 1} })
      }else  if (routeName == 'app_system_index') { //系统设置左滑，切换到首页
        this.handleBackHome()
      }else { //非首页左滑，返回上一页
        this.handleBack()
      }
    },

    //右滑动
    swiperright: function () {
      let routeName = this.$route.name
      if (routeName == 'dashboard' || routeName == 'home') { //首页右滑，切换到系统设置
        // this.$store.commit('SET_WORKBENCH_ROUTE', { name: 'app_system_index', params: {active: 1} })
      }else  if (routeName == 'app_system_index') { //系统设置右滑，切换到首页
        this.handleBackHome()
      }else { //非首页右滑，返回上一页
        this.handleBack()
      }
    },
    getStyle(isLabel,paddingLeft){
      let style= {fontSize: '11px',wordBreak: 'keep-all',fontWeight: 'bold', whiteSpace: 'nowrap', overflow: 'hidden',zoom:'80%', lineHeight: '11px', height: '11px', maxHeight: '11px'}
      if (isLabel == true )style.width= '30px'
      if (paddingLeft == true )style.paddingLeft= '4px'
      return style
    },

    getTdMaxWidth(isWordBreak){
      let style= {fontSize: '11px',overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis', maxWidth: '245px', width: '245px'}
      if (isWordBreak == true ){
        style.whiteSpace= 'normal'
        style.wordBreak= 'break-all'
        style.wordWrap= 'break-word'
        style.overflow= 'visible'
        style.textOverflow= ''
        style.width= '230px'
        style.maxWidth= '230px'
      }
      return style
    },
    rfidScan(type){
      switch (type) {
        case 1:  //开始扫描
          this.$notify.success('开始盘询，请稍候')
          this.scanBegin = true
          this.scanEnd = false
          setTimeout(() => {
            window.scanBegin()
          }, 1000)
          break;
        case 2:  //结束扫描
          this.$notify.success('结束扫描中，请稍候')
          this.showRfidScan = false
          setTimeout(() => {
            let rfidList = window.scanEnd()
            this.scanBegin = false
            this.scanEnd = true
            this.utils.loadHide()
            if (rfidList.length > 0) window.scanConfirm(rfidList)
          }, 1000)
          break;
        case 4:  //取消扫描
          this.showRfidScan = false
          scanEnd(true)
          break;
      }

    }
  },
  watch: {
    '$store.state.workbenchRoute': function (newRute) {
      this.$router.push(newRute).catch(() => null)
      if (newRute.name == 'dashboard') {
        this.transitionName = 'slide-left'
        this.active = 0
      } else {
        this.transitionName = 'slide-right'
        if (!newRute.params || !newRute.params.active) {
          this.active = -1
        } else{
          this.active = newRute.params.active
        }
      }
    },
    $route(now,old){     //监控路由变换，控制返回按钮的显示
      //振动效果
      this.utils.vibrate()
      if (now && now.meta  && now.meta.title) {
        this.nowTitle = now.meta.title
      } else {
        this.nowTitle = ''
      }

      if (now && now.name) {
        this.nowRouteName = now.name
      } else {
        this.nowRouteName = ''
      }

      /**设置目标路由参数，created之后可以通过 this.$route.params获取
       * 该方法返回的是对象 参考transfer-pick/detail.vue用法
       *  比如由拣货界面返回拣货列表的时候，将当前拣货主键传递过去，然后获取路由参数做其他使用
       */
      if (this.$refs.routerView.setRouteToParam) {
        let routeParam = this.$refs.routerView.setRouteToParam()
        if (routeParam) {
          if (!now.params) now.params = {}
          Object.keys(routeParam).forEach(key => {
            now.params[key] = routeParam[key]
          })
        }
      }
      this.isHome = now.path == "/dashboard" || now.path ==  '/' || now.path ==  ''
      if(now.path=="/dashboard"){
        this.handleBackHome()
      } else {

        //底部操作栏按钮增加振动效果
       setTimeout(() => {
         $('.footer-btn').find('button').click(() => {
           //振动效果
           this.utils.vibrate()
         })
       }, 500)
      }
    }
  },
  components: {
    Warehouse, Dialog, Field,RadioGroup, Radio, Sticky, FortenCode
  }
}
</script>
